import asyncio, pyautogui, random, time, json, os
from pynput import keyboard, mouse
from threading import Event

from core.base_controller import BaseController
from core.utils import focus_wow


class RecordEventsController(BaseController):
    def __init__(self, task_list, ws_client):
        super().__init__(task_list, ws_client)
        self.events = []
        self.start_time = None
        self.is_recording = False
        self.stop_event = Event()
        self.keyboard_listener = None
        self.mouse_listener = None
        self.extra_data = {}

    def start(self, extra_data):
        self.extra_data = extra_data
        """开始录制键盘鼠标操作"""
        if self.is_recording:
            print("Recording is already in progress")
            return
        self.log("RecordEventsController Start")
        self.events = []
        self.is_recording = True
        self.stop_event.clear()
        self.start_time = time.time()

        # 键盘监听器
        self.keyboard_listener = keyboard.Listener(
            on_press=self._on_press, on_release=self._on_release
        )

        # 鼠标监听器
        self.mouse_listener = mouse.Listener(
            on_move=self._on_move, on_click=self._on_click, on_scroll=self._on_scroll
        )

        self.keyboard_listener.start()
        self.mouse_listener.start()

        print("Recording started...")

    def stop(self):
        """停止录制并返回录制的事件"""
        if not self.is_recording:
            print("No recording in progress")
            return
        self.log("RecordEventsController Stop")
        self.is_recording = False
        self.stop_event.set()

        if self.keyboard_listener:
            self.keyboard_listener.stop()
        if self.mouse_listener:
            self.mouse_listener.stop()

        print(f"Recording stopped. Total events recorded: {len(self.events)}")
        return self.events

    
    def stop_and_save_to_file(self):
        events = self.stop()
        events_dir = os.getenv("EVENTS_DIR")
        filename = self.extra_data.get("save_filename", "未命名")
        timestamp = int(time.time())  # 当前 Unix 时间戳
        new_filename = f"{filename}_{timestamp}.json"
        # new_filename = "abs_1753415202.json"
        file_path = os.path.join(events_dir, new_filename)
        self.save_to_file(file_path)
        return events
      
    def save_to_file(self, filename):
        """将录制的事件保存到文件"""
        with open(filename, "w") as f:
            json.dump(self.events, f)
        self.log(f"Recording saved to {filename}")

    def _get_timestamp(self):
        return time.time() - self.start_time

    def _on_press(self, key):
        self.events.append(
            {"time": self._get_timestamp(), "type": "key_press", "key": str(key)}
        )

    def _on_release(self, key):
        self.events.append(
            {"time": self._get_timestamp(), "type": "key_release", "key": str(key)}
        )

    def _on_move(self, x, y):
        self.events.append(
            {"time": self._get_timestamp(), "type": "mouse_move", "x": x, "y": y}
        )

    def _on_click(self, x, y, button, pressed):
        self.events.append(
            {
                "time": self._get_timestamp(),
                "type": "mouse_click",
                "x": x,
                "y": y,
                "button": str(button),
                "pressed": pressed,
            }
        )

    def _on_scroll(self, x, y, dx, dy):
        self.events.append(
            {
                "time": self._get_timestamp(),
                "type": "mouse_scroll",
                "x": x,
                "y": y,
                "dx": dx,
                "dy": dy,
            }
        )
